#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
洪水预报参数收集器使用示例

演示如何使用FloodForecastParameterCollector进行对话式参数收集
"""

from .parameter_collector import FloodForecastParameterCollector
import json
import sys
from loguru import logger

# 配置loguru日志
logger.remove()  # 移除默认配置

# 控制台日志 - 显示INFO及以上级别
logger.add(
    sys.stdout,
    level="INFO",
    format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
    colorize=True
)

# 文件日志 - 详细日志，包含DEBUG级别
logger.add(
    "logs/flood_forecast_example_usage.log",
    level="DEBUG",
    format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {name}:{function}:{line} | {process.id} | {thread.id} - {message}",
    rotation="10 MB",
    retention="7 days",
    compression="zip",
    encoding="utf-8"
)

# 错误日志单独文件
logger.add(
    "logs/flood_forecast_example_usage_error.log",
    level="ERROR",
    format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {name}:{function}:{line} | {process.id} | {thread.id} - {message}\n{exception}",
    rotation="5 MB",
    retention="30 days",
    compression="zip",
    encoding="utf-8"
)

def interactive_demo():
    """交互式演示"""
    print("🌊 洪水预报参数收集系统演示")
    print("=" * 50)
    print("请输入您的洪水预报需求，系统将引导您完善所需参数")
    print("输入 'quit' 退出演示")
    print()
    
    # 创建收集器实例
    collector = FloodForecastParameterCollector()
    
    while True:
        user_input = input("👤 您: ").strip()
        
        if user_input.lower() in ['quit', 'exit', '退出']:
            print("👋 再见！")
            break
            
        if not user_input:
            continue
            
        # 处理用户输入
        result = collector.process_user_input(user_input)
        
        # 显示AI回复
        print(f"🤖 AI助手: {result['response']}")
        print()
        
        # 显示当前状态
        print(f"📊 状态: {result['status']}")
        if result['extracted_this_turn']:
            print(f"📝 本轮提取的参数: {result['extracted_this_turn']}")
        
        # 显示验证错误（如果有）
        if result.get('validation_errors'):
            print(f"⚠️ 验证错误: {result['validation_errors']}")
        
        print(f"✅ 已收集参数: {[k for k, v in result['parameters'].items() if v]}")
        print(f"❌ 缺失参数: {result['missing_parameters']}")
        
        # 显示完成百分比
        completion_pct = len([v for v in result['parameters'].values() if v]) / len(collector.required_parameters) * 100
        print(f"📈 完成度: {completion_pct:.1f}%")
        print("-" * 50)
        
        # 如果收集完成，显示最终JSON
        if result['status'] == 'completed':
            print("🎉 参数收集完成！")
            try:
                final_json = collector.get_final_parameters_json()
                print("\n📄 最终参数JSON:")
                print(final_json)
            except Exception as e:
                print(f"生成最终JSON时出错: {e}")
            
            # 询问是否重新开始
            restart = input("\n是否重新开始？(y/n): ").strip().lower()
            if restart in ['y', 'yes', '是']:
                collector.reset()
                print("\n🔄 已重置，请重新输入需求...")
                print("-" * 50)
            else:
                break

def batch_demo():
    """批量测试演示"""
    print("\n🧪 批量测试演示")
    print("=" * 50)
    
    # 测试用例
    test_cases = [
        {
            "name": "完整信息测试",
            "inputs": [
                "我要做一个大伙房水库的新安江预报，预测未来流量，从2024-01-15 08:00开始，预报48小时，降雨预见期12小时"
            ]
        },
        {
            "name": "分步收集测试",
            "inputs": [
                "我要做洪水预报",
                "大伙房水库",
                "新安江模型",
                "预测流量",
                "明天上午8点开始",
                "预报72小时",
                "降雨预见期24小时"
            ]
        },
        {
            "name": "部分信息测试",
            "inputs": [
                "三峡水库流量预报，48小时",
                "用萨克拉门托模型",
                "2024-02-01 06:00开始",
                "降雨预见期6小时"
            ]
        },
        {
            "name": "验证和确认测试",
            "inputs": [
                "我要做洪水预报，水库名称是ABC，预报模型用XYZ，时间是明天，预报200小时，降雨预见期100小时，预测变量是温度",
                "水库名称改为大伙房水库，预报模型改为新安江模型，预报时长改为48小时，降雨预见期改为12小时，预测变量改为流量",
                "确认"
            ]
        }
    ]
    
    for i, test_case in enumerate(test_cases, 1):
        print(f"\n🔬 测试用例 {i}: {test_case['name']}")
        print("-" * 30)
        
        collector = FloodForecastParameterCollector()
        
        for j, user_input in enumerate(test_case['inputs'], 1):
            print(f"\n第{j}轮输入: {user_input}")
            result = collector.process_user_input(user_input)
            
            print(f"AI回复: {result['response'][:100]}..." if len(result['response']) > 100 else f"AI回复: {result['response']}")
            print(f"状态: {result['status']}")
            print(f"已收集: {len([v for v in result['parameters'].values() if v])}/6 个参数")
            
            # 显示验证错误（如果有）
            if result.get('validation_errors'):
                print(f"验证错误: {result['validation_errors']}")
            
            if result['status'] == 'completed':
                print("\n✅ 参数收集完成！")
                try:
                    final_json = collector.get_final_parameters_json()
                    final_params = json.loads(final_json)
                    print("最终参数:")
                    for key, value in final_params['forecast_request'].items():
                        if key not in ['created_at', 'request_id']:
                            print(f"  {key}: {value}")
                except Exception as e:
                    print(f"生成最终JSON时出错: {e}")
                break
        
        print("\n" + "=" * 50)

def api_integration_example():
    """API集成示例"""
    print("\n🔌 API集成示例代码")
    print("=" * 50)
    
    api_example = '''
# FastAPI集成示例
from fastapi import FastAPI
from flood_forecast.parameter_collector import FloodForecastParameterCollector

app = FastAPI()
collectors = {}  # 存储会话

@app.post("/collect_parameters")
async def collect_parameters(session_id: str, user_input: str):
    if session_id not in collectors:
        collectors[session_id] = FloodForecastParameterCollector()
    
    result = collectors[session_id].process_user_input(user_input)
    
    if result['status'] == 'completed':
        # 参数收集完成，可以调用预测模型
        final_params = collectors[session_id].get_final_parameters_json()
        # 这里可以通过MCP调用预测模型
        # model_result = call_prediction_model(final_params)
        
    return result

# LangChain集成示例
from langchain.tools import BaseTool

class FloodForecastParameterTool(BaseTool):
    name = "flood_forecast_parameter_collector"
    description = "收集洪水预报所需的参数信息"
    
    def _run(self, user_input: str) -> str:
        collector = FloodForecastParameterCollector()
        result = collector.process_user_input(user_input)
        return result['response']
'''
    
    print(api_example)

def main():
    """主函数"""
    print("🌊 洪水预报参数收集系统")
    print("选择演示模式:")
    print("1. 交互式演示")
    print("2. 批量测试演示")
    print("3. API集成示例")
    print("4. 退出")
    
    while True:
        choice = input("\n请选择 (1-4): ").strip()
        
        if choice == '1':
            interactive_demo()
        elif choice == '2':
            batch_demo()
        elif choice == '3':
            api_integration_example()
        elif choice == '4':
            print("👋 再见！")
            break
        else:
            print("❌ 无效选择，请重新输入")

if __name__ == "__main__":
    main()